package com.hframe.utils;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class SrteamUtil {
    static Logger log = Logger.getLogger(SrteamUtil.class);

    private class DataItem {
        public byte[] data = null;
        public int length = 0;
    }

    public byte[] getInputSrteam(InputStream input) throws IOException {
        List<DataItem> datas = new ArrayList<DataItem>();
        int length = 0;
        byte[] ret = null;
        int index = 0;
        while (true) {
            DataItem item = new DataItem();
            item.data = new byte[4096];
            item.length = input.read(item.data);
            if (item.length > 0) {
                length += item.length;
                datas.add(item);
                index++;
            } else {
                break;
            }
        }

        if (length > 0) {
            ret = new byte[length];
        }

        int start = 0;
        for (int i = 0; i < index; i++) {
            System.arraycopy(datas.get(i).data, 0, ret, start, datas.get(i).length);
            start += datas.get(i).length;
        }

        return ret;
    }

    public String getInputString(InputStream input) {
        try {
            byte[] data = getInputSrteam(input);
            if (data != null && data.length > 0) {
                return new String(data);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return "";
    }
}
